#include "threadPool.h"
void *threadFunc(void * arg){
    threadPool_t * pthreadPool = (threadPool_t *)arg;
    while(1){
        // 取出任务
        pthread_mutex_lock(&pthreadPool->mutex);
        while(pthreadPool->taskQueue.queueSize == 0 && pthreadPool->exitflag == 0){
            pthread_cond_wait(&pthreadPool->cond,&pthreadPool->mutex);
        }
        if(pthreadPool->exitflag == 1){
            pthread_mutex_unlock(&pthreadPool->mutex);
            pthread_exit(NULL);
        }
        printf("worker got a task!\n");
        int netfd = pthreadPool->taskQueue.pfront->fd;
        Dequeue(&pthreadPool->taskQueue);
        pthread_mutex_unlock(&pthreadPool->mutex);
        
        transFile(netfd);
        close(netfd);
    }
}
//void unlock(void *arg){
//    threadPool_t * pthreadPool = (threadPool_t *)arg;
//    pthread_mutex_unlock(&pthreadPool->mutex);
//}
//void *threadFunc(void * arg){
//    threadPool_t * pthreadPool = (threadPool_t *)arg;
//    while(1){
//        // 取出任务
//        int netfd;
//        pthread_mutex_lock(&pthreadPool->mutex);
//        pthread_cleanup_push(unlock,pthreadPool);
//        while(pthreadPool->taskQueue.queueSize == 0){
//            pthread_cond_wait(&pthreadPool->cond,&pthreadPool->mutex);
//        }
//        printf("worker got a task!\n");
//        netfd = pthreadPool->taskQueue.pfront->fd;
//        Dequeue(&pthreadPool->taskQueue);
//        //pthread_mutex_unlock(&pthreadPool->mutex);
//        pthread_cleanup_pop(1);
//        
//        transFile(netfd);
//        close(netfd);
//    }
//}
int makeWorker(threadPool_t *pthreadPool){
    for(int i = 0; i < pthreadPool->workerNum; ++i){
        pthread_create(&pthreadPool->tidArr[i],NULL,threadFunc,pthreadPool);
    }
    return 0;
}
